﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Linq;
using System.ComponentModel;
using WPFExcelReport.Helpers;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for ProductionOrder.xaml
    /// </summary>
    public partial class YGRABDOC
    {
        string EXCLUDE = "01HMA";

        BindingListCollectionView cvGA
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(this.dlgGAAUF.ItemsSource);
            }
        }

        public double TargetRatio
        {
            get
            {
                double value = Convert.ToDouble(txtAddRatio.Text);
                //dwMaster["ABPSTKLG"] = value * 10000000;
                return value;
            }
            set
            {
                //2.设定TargetRatio，ABPSTKLG=ABPSOLLMENGE7*TargetRatio/ ABPSOLLMENGE5
                txtAddRatio.Text = value.ToString();
                double ABPSOLLMENGE5 = Convert.ToDouble(dwTABPOS["ABPSOLLMENGE5"].ToString());//120
                double ABPSOLLMENGE7 = Convert.ToDouble(dwTABPOS["ABPSOLLMENGE7"].ToString());//100
                if (ABPSOLLMENGE7 == 0)
                    ABPSOLLMENGE7 = ABPSOLLMENGE5;
                //VALUE=1.81
                //100*1.81
                //120*X=100*1.81,X=100/120*1.81
                dwTABPOS["ABPSTKLG"] = Math.Ceiling(value * 10000000 * ABPSOLLMENGE7 / ABPSOLLMENGE5);
                dwABPOS["ABPSTKLG"] = dwTABPOS["ABPSTKLG"];
            }
        }

        void vwGAAUF_CurrentChanged(object sender, EventArgs e)
        {
            if (dwGAAUF == null)
                return;
            if (SetStock.Tables.Contains("GLLG"))
            {
                SetStock.Tables["GLLG"].Clear();
            }
            if (SetStock.Tables.Contains("GAAUF"))
            {
                SetStock.Tables["GAAUF"].Clear();
            }
            if (dwGAAUF["GAKG1"].ToString().Trim() == "")
                return;
            SetData.ZUTEI.Clear();
            SetData.GAAUF.Clear();
            double GAKG1 = Convert.ToDouble(dwGAAUF["GAKG1"].ToString());
            double GAKG2 = Convert.ToDouble(dwGAAUF["GAKG2"].ToString());
            double GAKG3 = Convert.ToDouble(dwGAAUF["GAKG3"].ToString());
            double GAKG5 = Convert.ToDouble(dwGAAUF["GAKG5"].ToString());
            double REQ = (GAKG1 - GAKG2 - GAKG3 - GAKG5) / 100;
            double ALLQ = GAKG3 + GAKG5;
            txtRestReq.Text = REQ.ToString();
            if (REQ > 0 )
            {
                btnBook.IsEnabled = true;
                btnMPlan.IsEnabled = true;
            }
            else
            {
                btnBook.IsEnabled = true;
                btnMPlan.IsEnabled = false;
            }
            if(IsSave)
            {
                btnBook.IsEnabled = false;
            }
            if (ALLQ > 0)
            {
                btnRemoveBook.IsEnabled = true;
            }
            else
            {
                btnRemoveBook.IsEnabled = false;
            }
            string filter = "GAART='" + dwGAAUF["GAART"].ToString() + "' AND GAFARBE='" + dwGAAUF["GAFARBE"].ToString() + "' AND GAAUFMSL='" + dwGAAUF["GAAUFMSL"].ToString() + "'";
            cvMGAAUF.CustomFilter = filter;
            if (vwYGAAUF.View != null)
            {
                vwYGAAUF.View.MoveCurrentToFirst();
            }
            if (dwYGAAUF == null)
            { 
                loadstock(dwGAAUF);
            }

            //RefreshRatio();
        }

        void vwYGAAUF_CurrentChanged(object sender, EventArgs e)
        {
            loadstock(dwYGAAUF);
        }
        public void loadstock(DataRow dwYARN)
        {
            try
            {
                if (dwYARN == null)
                    return;

                DataSet SResult;
                DataRow dwData = SetData.ICC_QUERYTB.NewRow();
                dwData["GAMANDANT"] = dwYARN["GAMANDANT"];
                dwData["GAART"] = dwYARN["GAART"];
                dwData["GAFARBE"] = dwYARN["GAFARBE"];
                dwData["C20"] = EXCLUDE;
                /*    DataSet SResult = INTEXDBC.QueryGAAUF(dwData, 8);
                    SetDetail.Tables["GAAUF"].Clear();
                    SetDetail.Merge(SResult);
                     SResult = INTEXDBC.QueryGAAUF(dwData, 10);
                    SetData.Tables["GAAUF"].Clear();
                     SetData.Merge(SResult);
                    */
                SResult = INTEXDBC.QueryGAAUF(dwData, 12);
                SResult.Tables[0].TableName = "GAAUF";
                if (SetStock.Tables.Contains("GAAUF"))
                {
                    SetStock.Tables["GAAUF"].Clear();
                }
                SetStock.Merge(SResult);
                SResult = INTEXDBC.QueryGAAUF(dwData, 121);
                SResult.Tables[0].TableName = "GAAUF";
                SetStock.Merge(SResult);

                string part = dwGAAUF["GABEM"].ToString().Trim();
                this.cvYARNA.CustomFilter = "LO='01' AND GLAUFMSL='" + dwGAAUF["GAAUFMSL"].ToString() + "' AND (GPSPPART LIKE '" + part + "%' OR GPFBPART LIKE '" + part + "%' )";
                SResult = INTEXDBC.QueryGAAUF(dwData, 13);
                //
                foreach (DataRow row in SResult.Tables[0].Rows)
                {
                    string LO = row["LO"].ToString();
                    string LB = row["LB"].ToString();
                    string LP = row["LP"].ToString();
                    string PLACE = (LO + LB + LP.Trim());
                    foreach (DataRow ZU in SetStock.Tables["GAAUF"].Rows)
                    {
                        string ZULO = ZU["LO"].ToString();
                        string ZULB = ZU["LB"].ToString();
                        string ZULP = ZU["LP"].ToString();
                        string ZUPLACE = (ZULO + ZULB + ZULP.Trim());
                        if (ZULO + ZULB != LO + LB) continue;
                        if (PLACE.StartsWith(EXCLUDE)
                            && !ZUPLACE.StartsWith(EXCLUDE))
                        {
                            continue;
                        }

                        if (!PLACE.StartsWith(EXCLUDE)
                       && ZUPLACE.StartsWith(EXCLUDE)) continue;

                        if (ZU["GAART"].ToString() + ZU["GAVAR"].ToString() + ZU["GAFARBE"].ToString() + ZU["GPSPPART"].ToString() + ZU["GPFBPART"].ToString() + ZU["GLAUFMSL"].ToString()
                        != row["GAART"].ToString() + row["GAVAR"].ToString() + row["GAFARBE"].ToString() + row["GPSPPART"].ToString() + row["GPFBPART"].ToString() + row["GLAUFMSL"].ToString())
                            continue;
                        double NETKG = Convert.ToDouble(ZU["NETKG"].ToString());
                        double locked = Convert.ToDouble(ZU["QLOCK"].ToString());
                        double nLock = Convert.ToDouble(row["QLOCK"].ToString());
                        double QISSUE = Convert.ToDouble(row["QISSUE"].ToString());
                        ZU["QLOCK"] = locked + nLock - QISSUE;
                        ZU["QFREE"] = Math.Round(NETKG - (locked + nLock - QISSUE), 1);
                    }
                }
                /*预扣数暂不使用
                SResult = INTEXDBC.QueryGAAUF(dwYGAAUF, 14);
                foreach (DataRow row in SResult.Tables[0].Rows)
                {
                    string GABEM = row["GABEM"].ToString().Trim();
                    if (GABEM == "")
                        continue;
                    var query = from DataRow ZU in SetStock.Tables["GAAUF"].AsEnumerable()
                                where ZU["GAART"].ToString() == row["GAART"].ToString()
                                && ZU["GAFARBE"].ToString() == row["GAFARBE"].ToString()
                                && ZU["GLAUFMSL"].ToString() == row["GAAUFMSL"].ToString()
                                select ZU;
                    //找到任意一条对应的记录，就跳出循环。
                    foreach (DataRow ZU in query)
                    {
                        if (ZU["GPSPPART"].ToString().Trim() == GABEM
                            || ZU["GPFBPART"].ToString().Trim() == GABEM
                            )
                        {
                            double NETKG = Convert.ToDouble(ZU["NETKG"].ToString());
                            double locked = Convert.ToDouble(ZU["QLOCK"].ToString());
                            double QPLAN = Convert.ToDouble(ZU["QPLAN"].ToString());
                            double nLock = Convert.ToDouble(row["QPLAN"].ToString());
                            ZU["QPLAN"] = QPLAN + nLock;
                            ZU["QFREE"] = Math.Round(NETKG - (locked + nLock + QPLAN), 1);
                            break;
                        }
                    }
                }*/
                if (vwYARNA.View != null)
                {
                    vwYARNA.View.MoveCurrentToFirst();
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        void vwGLLG_CurrentChanged(object sender, EventArgs e)
        {
            try
            {
                if (dwGLLG == null)
                    return;
                if (dwGAAUF == null)
                    return;
                string lot = cmbLot.Text;
                if (lot == "纺批")
                {
                    dwGAAUF["GABEM"] = dwGLLG["GPSPPART"];
                }
                else
                {
                    dwGAAUF["GABEM"] = dwGLLG["GPFBPART"];
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        void vwYARNA_CurrentChanged(object sender, EventArgs e)
        {
            try
            {
                if (dwYARNA == null)
                {
                    return;
                }
                if (dwYARNA["GAART"].ToString().StartsWith("2"))
                {
                    cmbLot.Text = "染批";
                }
                if (dwYARNA["GAART"].ToString().StartsWith("1"))
                {
                    cmbLot.Text = "纺批";
                    if (!dwYARNA["GLAUFMSL"].ToString().StartsWith("SM"))
                    {
                        cmbLot.Text = "染批";
                    }
                }
                string LO = dwYARNA["LO"].ToString();
                string LB = dwYARNA["LB"].ToString();
                string LP = dwYARNA["LP"].ToString();
                dwYARNA["ADDT"] = EXCLUDE;
                DataSet SResult;
                if ((LO + LB + LP.Trim()).StartsWith(EXCLUDE))
                {
                    SResult = INTEXDBC.QueryGLLG(dwYARNA, 5);
                }
                else
                {
                    SResult = INTEXDBC.QueryGLLG(dwYARNA, 2);
                }
                SetStock.Tables["GLLG"].Clear();
                SetStock.Merge(SResult);

                SResult = INTEXDBC.QueryGAAUF(dwYARNA, 17);
                SResult.Tables[0].TableName = "ZUTEI";
                SetData.ZUTEI.Clear();
                SetData.Merge(SResult);
                SResult = INTEXDBC.QueryGAAUF(dwYARNA, 18);
                SResult.Tables[0].TableName = "GAAUF";
                SetData.GAAUF.Clear();
                SetData.Merge(SResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        void vwMU_CurrentChanged(object sender, EventArgs e)
        {
            if (dwMU == null)
                return;
            try
            {
                string ABAAPOS = dwMU["ABAAPOS"].ToString();
                var qMU = from MUrow in SetDetail.Tables["ICC_ABAX"].AsEnumerable()
                          group MUrow by new
                          {
                              KRS = MUrow["ABAAUFKRS"].ToString(),
                              LFD = MUrow["ABAAUFLFD"].ToString(),
                              APOS = MUrow["ABAAPOS"].ToString(),
                          }
                              into g
                              select new
                              {
                                  KEY = g.Key,
                                  BATCHES = g.Max(XD => Convert.ToDouble(XD["ABASANZSTK"].ToString())),
                                  MQTY = g.Sum(XD => Convert.ToDouble(XD["ABARESMG"].ToString()) / 1000),
                              };
                foreach (var mu in qMU)
                {
                    if (mu.KEY.APOS == ABAAPOS)
                    {
                        BatchQty = Convert.ToDecimal(mu.MQTY);
                        Batches = Convert.ToDecimal(mu.BATCHES);
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        #region=====留位=====

        private void btnAddRatio_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwTABPOS == null)
                {
                    MessageBox.Show("请选择需要增投的生产单");
                    return;
                }

                double ABPSOLLMENGE5 = Convert.ToDouble(dwTABPOS["ABPSOLLMENGE5"].ToString());
                double ABPSOLLMENGE7 = Convert.ToDouble(dwTABPOS["ABPSOLLMENGE7"].ToString());
                double ADDQTY = (System.Math.Round(ABPSOLLMENGE7 * TargetRatio) - ABPSOLLMENGE7) / 100;
                if (100 * ADDQTY / ABPSOLLMENGE7 > 3)
                {
                    if (MessageBox.Show("投料量超出订单量两倍", "请确认", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    {
                        return;
                    }
                }
                txtAddQty.Text = ADDQTY.ToString();
                dwTABPOS["ABPSTKLG"] = Math.Ceiling(TargetRatio * 10000000 * ABPSOLLMENGE7 / ABPSOLLMENGE5);
                INTEXDBC.UpdateABPOS(dwTABPOS, 8);
                bool IsValid = false;
                DataSet SResult = INTEXDBC.QueryABPOS(dwTABPOS, 1);
                foreach (DataRow row in SResult.Tables[0].Rows)
                {
                    if (row["ABPSTKLG"].ToString() == dwTABPOS["ABPSTKLG"].ToString()) IsValid = true;
                }
                if (!IsValid)
                {
                    MessageBox.Show("投料比没有得到正确更新，请通知管理员。可以重新尝试一下。");
                    return;
                }
                //if (!IsRepair)
                //{
                //    Calculate_Click(null, null);
                //    btnAdjustGAAUF_Click(null, null);
                //}
                //VALUE=1.81
                //100*1.81
                //120*X=100*1.81,X=100/120*1.81

                vwGAAUF.View.MoveCurrentToFirst();
            }
            catch (Exception ex)
            {
                MessageBox.Show("调整比例出现错误" + ex.Message);
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void btnRepQty_Click(object sender, RoutedEventArgs e)
        {
            try
            {  
                double ABPSOLLMENGE5 = Convert.ToDouble(dwTABPOS["ABPSOLLMENGE5"].ToString());
                double ABPSOLLMENGE7 = Convert.ToDouble(dwTABPOS["ABPSOLLMENGE7"].ToString());
                double RepQty = Convert.ToDouble(txtRepQty.Text.ToString());
                double ADDQTY = (System.Math.Round(ABPSOLLMENGE7 * TargetRatio) - ABPSOLLMENGE7) / 100;
                txtAddQty.Text = (ADDQTY+RepQty).ToString();
                this.txtAddRatio.Text = (System.Math.Round(100 * (ADDQTY+RepQty) / ABPSOLLMENGE7 + 1, 4)).ToString();
                dwTABPOS["ABPSTKLG"] = Math.Ceiling(TargetRatio * 10000000 * ABPSOLLMENGE7 / ABPSOLLMENGE5);
                INTEXDBC.UpdateABPOS(dwTABPOS, 8);
                 string GAPOS="";
                var query = from DataRow row in SetDetail.Tables["GAAUF"].AsEnumerable()
                            where row["GABEM"].ToString().Trim() == "*HX*"
                            select row;
                foreach (DataRow row in query)
                {
                    GAPOS = dwGAAUF["GAPOS"].ToString();
                }
                if (GAPOS == "")
                    return;
                var qTotal = (from GA in SetDetail.Tables["GAAUF"].AsEnumerable()
                              where GA["GASA"].ToString() == "713"
                              && GA["GABEM"].ToString().Trim() != "*HX*"
                              select Convert.ToDouble(GA["GAKG1"].ToString())).Sum();
                double TQTY = (qTotal + 100 * RepQty)/100;
                double ratio = 0;
                double Total = 0;
                //4.计算用量，GAKG1= ABPSOLLMENGE7*TargetRatio*GASP1,ABPSOLLMENGE5*ABPSTKLG
                //5.GABASMG2=GAKG1/ABPSOLLMENGE5
                foreach (DataRow GA in SetDetail.Tables["GAAUF"].Rows)
                {
                    string GASA = GA["GASA"].ToString();
                    if (GASA == "310") continue;
                    double GASP1 = Convert.ToDouble(GA["GASP1"].ToString()) * 0.001 * 0.01;
                    double MRatio = 0;
                    double GAKG1 = 0;
                    double GABASMG2 = 0;
                    GA["GABASMG2"] = 0;
                    if (GA["GAPOS"].ToString() == GAPOS)//按比例算重量
                    {
                        ratio = RepQty / TQTY;
                        GASP1 = Math.Round(ratio * 10000) / 10000;
                        MRatio = GASP1 * TargetRatio;
                        GA["GASP1"] = GASP1 * 1000 * 100;
                        GAKG1 = 100 * RepQty;
                        GABASMG2 = Math.Round(100 * RepQty / ABPQTY * 1000);
                        GA["GAKG1"] = GAKG1;
                        GA["GABASMG2"] = GABASMG2;
                    }
                    else//重量不变
                    {
                        GAKG1 = Convert.ToDouble(GA["GAKG1"].ToString());
                        ratio = GAKG1*0.01 / TQTY;
                        GASP1 = Math.Round(ratio* 10000) / 10000;                      
                        GA["GASP1"] = GASP1 * 1000 * 100;
                        MRatio = GASP1 * TargetRatio;                       
                        GABASMG2 = Math.Round(GAKG1 / ABPQTY * 1000);
                        GA["GABASMG2"] = GABASMG2;
                    }
                    Total += MRatio;
                }
                if (Math.Round(Total / TargetRatio * 100) != 100)
                {
                    MessageBox.Show("比例有误!");
                }


                btnAdjustGAAUF_Click(null, null);

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void btnAddQty_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwTABPOS == null)
                {
                    MessageBox.Show("请选择需要增投的生产单");
                }
                double ABPSOLLMENGE5 = Convert.ToDouble(dwTABPOS["ABPSOLLMENGE5"].ToString());
                double ABPSOLLMENGE7 = Convert.ToDouble(dwTABPOS["ABPSOLLMENGE7"].ToString());
                double ADDQTY = Convert.ToDouble(txtAddQty.Text.ToString());
                this.txtAddRatio.Text = (System.Math.Round(100 * ADDQTY / ABPSOLLMENGE7 + 1, 4)).ToString();
                //btnAddRatio_Click(null, null);
                Calculate_Click(null, null);
                btnAdjustGAAUF_Click(null, null);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void btnToAllocation_Click(object sender, RoutedEventArgs e)
        {
            MUREQ.Focus();
            btnListMUReq_Click(null, null);
        }

        private void btnAllocate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwGAAUF == null)
                {
                    MessageBox.Show("请选择要保存的纱线!");
                    return;
                }
                if (dwGLLG == null)
                {
                    MessageBox.Show("请选择要留位的记录!");
                    return;
                }
                dwGAAUF["GAVAR"] = Helper.Left(dwGAAUF["GAVAR"].ToString().PadRight(3), 3);
                string GLLBEHI = dwGLLG["GLLBEHI"].ToString();

                string GPBPARTIE = dwGLLG["GPBPARTIE"].ToString();
                string GPSPPART = dwGLLG["GPSPPART"].ToString();
                string GPFBPART = dwGLLG["GPFBPART"].ToString();
                string LPLBKZ = dwGLLG["LPLBKZ"].ToString();
                if (LPLBKZ.Trim() == "L")
                    LPLBKZ = "S";

                double GPBBSTKGZ = Convert.ToDouble(dwGLLG["GPBBSTKGZ"].ToString());

                double KG = Convert.ToDouble(dwGLLG["KG"].ToString());
                double FREEKG = Convert.ToDouble(dwGLLG["FREEKG"].ToString());
                double ALLOKG = Convert.ToDouble(dwGLLG["ALLOKG"].ToString());
                double GAKG1 = Convert.ToDouble(dwGAAUF["GAKG1"].ToString());
                double GAKG2 = Convert.ToDouble(dwGAAUF["GAKG2"].ToString());
                double GAKG3 = Convert.ToDouble(dwGAAUF["GAKG3"].ToString());
                double GAKG5 = Convert.ToDouble(dwGAAUF["GAKG5"].ToString());
                double REQ =Helper.RoundX((GAKG1 - GAKG2 - GAKG3 - GAKG5) / 100, 1000);
                if (REQ <= 0)
                    return;
                #region===dwZUTEI========
                DataRow dwZUTEI = INTEXDBC.Convert2ZUTEI(null, app.company, false);

                dwZUTEI["ZUMANDANT"] = dwGAAUF["GAMANDANT"];
                dwZUTEI["ZUAUFKRS"] = dwGAAUF["GAAUFKRS"];
                dwZUTEI["ZUAUFLFD"] = dwGAAUF["GAAUFLFD"];
                dwZUTEI["ZUAUFPOS"] = dwGAAUF["GAAUFPOS"];
                dwZUTEI["ZUSA"] = dwGAAUF["GASA"];
                dwZUTEI["ZUTEILNR"] = "0000";
                dwZUTEI["ZUPOS"] = dwGAAUF["GAPOS"];
                dwZUTEI["ZUART"] = dwGAAUF["GAART"];
                dwZUTEI["ZUVAR"] = dwGAAUF["GAVAR"];
                dwZUTEI["ZUFARBE"] = dwGAAUF["GAFARBE"];
                dwZUTEI["ZUNEUBEN"] = m_Data.UserID;
                dwZUTEI["ZUNEUDAT"] = m_Data.date;

                dwZUTEI["ZUFLAG"] = LPLBKZ;

                dwZUTEI["ZUPARTIE"] = GPBPARTIE;
                dwZUTEI["ZUPARTIEKZ"] = dwGLLG["GPBPARTIEKZ"];
                dwZUTEI["ZULO"] = dwGLLG["GLLO"];
                dwZUTEI["ZULB"] = dwGLLG["GLLB"];
                dwZUTEI["ZULBEHI"] = GLLBEHI;
                dwZUTEI["ZUSPPART"] = dwGLLG["GPSPPART"];
                //验证是否同一箱已经留位了
                DataSet SResult = m_Data.ZU.QueryZUTEI(dwZUTEI, 11);
                if (SResult.Tables[0].Rows.Count > 0)
                {
                    throw new Exception("同一箱号不允许重复留位");
                }
                #endregion
                #region====FREEKG > REQ======
                if (FREEKG <= REQ)
                {
                    //需求100，此箱50
                    REQ = FREEKG;
                }
                ALLOKG += REQ;
                FREEKG -= REQ;
                GPBBSTKGZ += REQ * 1000;
                dwGLLG["ALLOKG"] = ALLOKG;
                dwGLLG["FREEKG"] = FREEKG;
                dwGLLG["GPBBSTKGZ"] = GPBBSTKGZ;
                dwZUTEI["ZUEINTKG"] = REQ * 1000;

                if (LPLBKZ == "P")
                {
                    GAKG5 += REQ * 100;
                }
                else
                {
                    GAKG3 += REQ * 100;
                }
                dwGAAUF["GAKG3"] = GAKG3;
                dwGAAUF["GAKG5"] = GAKG5;
                if (GPFBPART.Trim().Length < 3)
                {
                    dwGAAUF["GABEM"] = dwGLLG["GPSPPART"];
                }
                else
                {
                    dwGAAUF["GABEM"] = dwGLLG["GPFBPART"];
                }

                txtRestReq.Text = ((GAKG1 - GAKG2 - GAKG3 - GAKG5) / 100).ToString();
                #endregion
                
                m_Data.ZU.InsertZUTEI(dwZUTEI, app.company);

                GBW.NWBBEW(dwZUTEI, "61", this.RUNID);
                INTEXDBC.UpdateGAAUF(dwGAAUF, 1);
                INTEXDBC.UpdateGPBST(dwGLLG, 3);
                SetData.Tables["ZUTEI_ITX"].Rows.Add().ItemArray = dwZUTEI.ItemArray;                
                
                DataRow dwData = SetEnv.ICC_QUERYTB.NewRow();
                dwData["ABPMANDANT"] = dwGAAUF["GAMANDANT"];
                dwData["ABPAUFKRS"] = dwGAAUF["GAAUFKRS"];
                dwData["ABPAUFLFD"] = dwGAAUF["GAAUFLFD"];
                dwData["ABPAUFPOS"] = dwGAAUF["GAAUFPOS"];
                INTEXDBC.UpdateABPOS(dwData, 6);
                string part = dwGAAUF["GABEM"].ToString().Trim();
                this.cvYARNA.CustomFilter = "LO='01' AND GLAUFMSL='" + dwGAAUF["GAAUFMSL"].ToString() + "' AND (GPSPPART LIKE '" + part + "%' OR GPFBPART LIKE '" + part + "%' )";
                ResetTab();
                IsINBookingmode = true;
                IsRatio = false;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
                MessageBox.Show(ex.Message);
            }
        }

        private void btnSaveGAAUF_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwGAAUF == null)
                {
                    MessageBox.Show("请选择要保存的纱线");
                    return;
                }
                dwGAAUF["GAART"] = Helper.Left(dwGAAUF["GAART"].ToString().PadRight(20), 20);
                dwGAAUF["GAVAR"] = Helper.Left(dwGAAUF["GAVAR"].ToString().PadRight(3), 3);
                dwGAAUF["GAFARBE"] = Helper.Left(dwGAAUF["GAFARBE"].ToString().PadRight(10), 10);
                if (dwGAAUF["GABEM"].ToString().Trim().Length < 2)
                {
                    dwGAAUF["GABEM"] = " ".PadRight(39);
                }
                dwGAAUF["GABEM"] = Helper.Left(dwGAAUF["GABEM"].ToString().PadRight(40), 40);
                DataSet SResult = INTEXDBC.QueryGSCOLOR(dwGAAUF, 5);
                if (SResult.Tables[0].Rows.Count == 0)
                {
                    throw new Exception("纱线:" + dwGAAUF["GAART"].ToString() + dwGAAUF["GAVAR"].ToString() + dwGAAUF["GAFARBE"].ToString() + dwGAAUF["GAAUFMSL"].ToString() + ",不存在，请核对编码");

                }

                if (dwYARNA != null)
                {
                    if (cmbLot.Text.Trim() == "")
                    {
                        MessageBox.Show("请选择批次类型");

                        return;
                    }
                    string GPSPPART = dwYARNA["GPSPPART"].ToString();
                    string GPFBPART = dwYARNA["GPFBPART"].ToString();
                    if (cmbLot.Text.Trim() == "纺批")
                    {
                        dwGAAUF["GABEM"] = Helpers.Helper.Left(GPSPPART.PadRight(40), 40);
                    }
                    else
                    {
                        dwGAAUF["GABEM"] = Helpers.Helper.Left(GPFBPART.PadRight(40), 40);
                    }
                }
                dwGAAUF["GAAUFMSL"] = dwGAAUF["GAAUFMSL"].ToString().ToUpper();                
                INTEXDBC.SaveGAAUF(dwGAAUF, "YGR");

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }

        private void RefreshRatio()
        {
            try
            {
                //GASP1=GABASMG2/ABPSTKLG
                var qTotal = (from GA in SetDetail.Tables["GAAUF"].AsEnumerable()
                              where GA["GASA"].ToString() == "713"
                              select Convert.ToDouble(GA["GAKG1"].ToString())).Sum();
                double Total = (double)qTotal;
                double TRatio = 0;
                double ABPSTKLG = Convert.ToDouble(dwTABPOS["ABPSTKLG"].ToString()) / 10000000;
                if (ABPSTKLG == 0)
                    ABPSTKLG = 1;
                foreach (DataRow row in SetDetail.Tables["GAAUF"].Rows)
                {
                    double GASP1 = 0;
                    GASP1 = Convert.ToDouble(row["GASP1"].ToString());

                    double GABASMG2 = Convert.ToDouble(row["GABASMG2"].ToString());
                    if (GASP1 == 0)
                    {
                        GASP1 = Math.Round(GABASMG2 * 0.1 / ABPSTKLG, 0) * 10;
                        row["GASP1"] = GASP1;
                    }
                    TRatio += GASP1 / 100000;
                }
                txtTRatio.Text = TRatio.ToString();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void Calculate_Click(object sender, RoutedEventArgs e)
        { 
            try
            {
                string filter = "(GAKG3>0 OR GAKG5>0 OR GAKG2>0) AND (GASA <>'310')";
                DataRow[] rows = SetDetail.Tables["GAAUF"].Select(filter); 
                if (rows.Length > 0)
                    throw new Exception("为了节约资源，你先把分盘取消,留位取消，再调整投料比行不行");
                btnAddRatio_Click(null, null);
                ResetTab();
                IsSave = true;
                btnBook.IsEnabled = false;
                double Total = 0;
                //4.计算用量，GAKG1= ABPSOLLMENGE7*TargetRatio*GASP1,ABPSOLLMENGE5*ABPSTKLG
                //5.GABASMG2=GAKG1/ABPSOLLMENGE5
                foreach (DataRow GA in SetDetail.Tables["GAAUF"].Rows)
                {
                    string GASA = GA["GASA"].ToString();
                    if (GASA == "310") continue;
                    double GASP1 = Convert.ToDouble(GA["GASP1"].ToString()) * 0.001 * 0.01;
                    double MRatio = GASP1 * TargetRatio;
                    double GAKG1 = Math.Round(VKPQTY * MRatio * 100);
                    GA["GABASMG2"] = Math.Round(GAKG1 / ABPQTY * 1000);
                    GA["GAKG1"] = GAKG1;
                    Total += MRatio;
                }
                if (Math.Round(Total / TargetRatio * 100) != 100)
                {
                    IsSave = false;
                    btnBook.IsEnabled = true;
                    MessageBox.Show("比例有误!");
                } 
                
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void txtRatio_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter && e.Key != Key.Return)
                return;
        }

        private void btnRemoveAllocate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                m_Data.GD.RemoveAllocation(dwGAAUF);
                double GAKG1 = Convert.ToDouble(dwGAAUF["GAKG1"].ToString());
                double GAKG2 = Convert.ToDouble(dwGAAUF["GAKG2"].ToString());
                double GAKG3 = Convert.ToDouble(dwGAAUF["GAKG3"].ToString());
                double GAKG5 = Convert.ToDouble(dwGAAUF["GAKG5"].ToString());
                txtRestReq.Text = ((GAKG1 - GAKG2 - GAKG3 - GAKG5) / 100).ToString();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void btnAdjustGAAUF_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                foreach (DataRow dwAUF in SetDetail.Tables["GAAUF"].Rows)
                {
                    
                    dwAUF["GAART"] = Helper.Left(dwAUF["GAART"].ToString().PadRight(20), 20);
                    dwAUF["GAVAR"] = Helpers.Helper.Left(dwAUF["GAVAR"].ToString().PadRight(3), 3);
                    dwAUF["GAFARBE"] = Helpers.Helper.Left(dwAUF["GAFARBE"].ToString().PadRight(10), 10);
                    dwAUF["GABEM"] = Helpers.Helper.Left(dwAUF["GABEM"].ToString().Trim().PadRight(40), 40);
                    dwAUF["GAAUFMSL"] = Helpers.Helper.Left(dwAUF["GAAUFMSL"].ToString().Trim().PadRight(2), 2);
                    //row["GASP1"] = 0;
                    DataSet SResult = INTEXDBC.QueryGSCOLOR(dwAUF, 5);
                    if (SResult.Tables[0].Rows.Count == 0)
                    {
                        throw new Exception("纱线:" + dwAUF["GAART"].ToString() + dwAUF["GAVAR"].ToString() + dwAUF["GAFARBE"].ToString() + dwAUF["GAAUFMSL"].ToString() + ",不存在，请核对编码");
                    }
                    string GASA = dwAUF["GASA"].ToString();
                    if (GASA == "310") continue;
                    double GASP1 = Convert.ToDouble(dwAUF["GASP1"].ToString()) * 0.001 * 0.01;
                    double MRatio = GASP1 * TargetRatio;
                    double GAKG1 = Math.Round(VKPQTY * MRatio * 100);

                     double cGAKG1=Convert.ToDouble(dwAUF["GAKG1"].ToString());
                    if(cGAKG1!=GAKG1)
                    {
                        if (!IsRepair)
                        {
                            throw new Exception("纱线:" + dwAUF["GAART"].ToString() + dwAUF["GAVAR"].ToString() + dwAUF["GAFARBE"].ToString() + dwAUF["GAAUFMSL"].ToString() + ",请计算投料比");
                        } 
                    }
                }
                foreach (DataRow dwAUF in SetDetail.Tables["GAAUF"].Rows)
                {
                    INTEXDBC.SaveGAAUF(dwAUF, "YGR");
                }
                btnListMUReq_Click(null, null);
                ResetTab();
                btnBook.IsEnabled = true;
            }
            catch (Exception ex)
            {
                IsCalculate = true;
                MessageBox.Show(ex.Message);
                Tracer.Error(ex.StackTrace, ex);
            }

        }

        private void btnDelGAAUF_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwGAAUF == null)
                {
                    MessageBox.Show("请选择要删除的纱线");
                    return;
                }
                if (txtGADel.Text.ToString().Trim() != "Y")
                {
                    MessageBox.Show("必须手动设置后面标志为Y");
                    return;
                }
                m_Data.GD.RemoveAllocation(dwGAAUF);
                INTEXDBC.DeleteGAAUF(dwGAAUF, 1);
                string _KRS = dwGAAUF["GAAUFKRS"].ToString();
                string _LFD = dwGAAUF["GAAUFLFD"].ToString();
                string _POS = dwGAAUF["GAAUFPOS"].ToString();
                string _aPOS = dwGAAUF["GAPOS"].ToString();
                vwGAAUF.View.MoveCurrentTo(-1);
                string filter = "GAAUFKRS='" + _KRS + "' AND GAAUFLFD='" + _LFD + "' AND GAAUFPOS='" + _POS + "' AND GASA=713 AND GAPOS='" + _aPOS + "'";
                DataRow[] rows = SetData.Tables["GAAUF"].Select(filter);
                foreach (DataRow row in rows)
                {

                    row.Delete();
                }
                rows = SetDetail.Tables["GAAUF"].Select(filter);
                foreach (DataRow row in rows)
                {
                    row.Delete();
                }
                SetDetail.AcceptChanges();
                txtGADel.Text = "N";
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        int idx = 0;
        public void GridEditCommand(object sender, RoutedEventArgs e)
        {
            if (idx == 0)
            {
                idx++;
                MessageBox.Show("在进行列表编辑前，请确认取消了要修改的行的留位,以便节约社会资源。若已经确认，请再点击一下这个按钮");
            }
            else
            {
                idx++;
            }
            if (idx == 1)
                return;
            else
            {
                IsGridEdit = true;
                idx = 0;
            }
        }
        #endregion
    }
}
